package com.dingwen.treasure.code.generate.util;

import cn.hutool.core.io.FileUtil;
import com.dingwen.treasure.base.constant.GlobalConstant;
import freemarker.template.Template;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.util.Map;

/**
 * 　FreeMarkerUtil
 * 　@author dingwen
 * 　@date 2022/7/13
 */
@Component
public class FreeMarkerUtil {

    /**
     * freeMarkerConfigurer
     */
    @Resource
    private FreeMarkerConfigurer freeMarkerConfigurer;


    /**
     * 生成
     *
     * @param params       参数
     * @param templatePath 样板
     * @param targetPath   目标
     */
    @SneakyThrows
    @SuppressWarnings("ALL")
    public void generate(Map<String, Object> params, String templatePath, String targetPath) {
        // 加载模版文件
        Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templatePath, GlobalConstant.UTF8);
        // 目标文件存储位置
        File file = FileUtil.file(targetPath);
        @Cleanup
        FileWriter fileWriter = new FileWriter(file);
        template.process(params, fileWriter);
    }
}
